package fr.univ.context.utilities;

import java.util.Calendar;
import java.util.List;

import fr.univ.context.process.R;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class CustomAdapter extends BaseAdapter {
	
	public static boolean SHOW_DIALOG = false;
	private static final int REQUEST_CODE = 0;
	
	private List<String> listTextOpt;
	private LayoutInflater mInflater;
	
	private ListActivity contextAct;
	private Intent intService;
	
	private Preferences preferences;
	private boolean flag;
	
	private PendingIntent pintent;
	private AlarmManager alarm;
	
	
	public CustomAdapter( ListActivity act , List<String> list ){
		
		this.listTextOpt = list;
		this.contextAct = act;
		flag = true;
		
		preferences = new Preferences(contextAct);
		intService = new Intent("fr.univ.context.mobile.START");
		mInflater = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		return listTextOpt.size();
	}

	@Override
	public Object getItem(int position) {
		return listTextOpt.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public int getViewTypeCount() {
	   return 3; //return 3, we have two types that the getView() method will return
	}

	@Override
	public boolean isEnabled(int position) {
        
		if (flag)
			return true;
		else
			return false;
    }
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		String itemOp = (String) getItem(position);
		View v = null;
		
		if ( convertView == null ) {
			
			if (itemOp.equals(Constants.TICKER_SYMBOLS[0])) {
				
				v = mInflater.inflate(R.layout.control_service, null);
				
				final ToggleButton tb = (ToggleButton) v.findViewById(R.id.tb_control_service);
				
				if ( isServiceRunning() ){
					tb.setChecked(true);					
					flag = false;
				}else{
					tb.setChecked(false);
					flag = true;
				}
				
				tb.setOnClickListener( new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						if (tb.isChecked()) {
							
							Log.i("Exec", "Service ON *********");
							flag = false;
							isEnabled(1);
							setStateRowsListActivity(R.color.gray, 80, false);
							
							int TIME_SLEEP = preferences.loadTimeSleep();
							
							Calendar cur_cal = Calendar.getInstance();
		                    cur_cal.setTimeInMillis(System.currentTimeMillis());
		                    cur_cal.add(Calendar.SECOND, 0);
		                    
							pintent = PendingIntent.getService(contextAct, REQUEST_CODE , intService, PendingIntent.FLAG_UPDATE_CURRENT);
							alarm = (AlarmManager) contextAct.getSystemService(Context.ALARM_SERVICE);
							alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), TIME_SLEEP * 60000, pintent);
						
						}else{
							
							Log.i("Exec", "Service OFF *********");
							flag = true;
							isEnabled(1);
							setStateRowsListActivity(R.color.white, 255, true);
							
							pintent = PendingIntent.getService(contextAct,  REQUEST_CODE , intService, PendingIntent.FLAG_UPDATE_CURRENT);
							alarm = (AlarmManager) contextAct.getSystemService(Context.ALARM_SERVICE);
							alarm.cancel(pintent);
							contextAct.stopService(intService);
						}
					}
				});
			
			} else if (itemOp.equals(Constants.TICKER_SYMBOLS[1])) {
				
				Preferences pref = new Preferences(contextAct);
				v = mInflater.inflate(R.layout.set_interval, null);
				
				TextView tv = (TextView) v.findViewById(R.id.subtitle_set_interval);
				tv.setText(pref.loadTimeSleep() + " minutes");
				
				if (isServiceRunning()) {
					
					TextView t1 = (TextView) v.findViewById(R.id.title_set_interval);
					t1.setTextColor(contextAct.getResources().getColor(R.color.gray));
					
					tv.setTextColor(contextAct.getResources().getColor(R.color.gray));
					
					ImageView im1 = (ImageView) v.findViewById(R.id.im_main_set_interval);
					im1.setAlpha(80);
					
					ImageView im2 = (ImageView) v.findViewById(R.id.im_sec_set_interval);
					im2.setAlpha(80);
				}
				
			} else if (itemOp.equals(Constants.TICKER_SYMBOLS[2])) {
				
				v = mInflater.inflate(R.layout.delete_database, null);
				
				if (isServiceRunning()) {
					
					ImageView im3 = (ImageView) v.findViewById(R.id.im_delete_database);
					im3.setAlpha(80);
					
					TextView t3 = (TextView) v.findViewById(R.id.title_delete_database);
					t3.setTextColor(contextAct.getResources().getColor(R.color.gray));
				}
				
			} else if (itemOp.equals(Constants.TICKER_SYMBOLS[3])) {
				
				v = mInflater.inflate(R.layout.control_dialog, null);
				
				final ToggleButton tb = (ToggleButton) v.findViewById(R.id.tb_control_dialog);
				
				if ( isServiceRunning() ){
					
					TextView t1 = (TextView) v.findViewById(R.id.title_control_dialog);
					t1.setTextColor(contextAct.getResources().getColor(R.color.gray));
					
					TextView t2 = (TextView) v.findViewById(R.id.subtitle_control_dialog);
					t2.setTextColor(contextAct.getResources().getColor(R.color.gray));
					
					ImageView im1 = (ImageView) v.findViewById(R.id.im_control_dialog);
					im1.setAlpha(80);
					
					tb.setEnabled(false);										
				}
				
				if (preferences.loadFlagDialog())
					tb.setChecked(true);
				else
					tb.setChecked(false);
					
				tb.setOnClickListener( new View.OnClickListener() {
					
					public void onClick(View v) {
						
						if (tb.isChecked()) {
							SHOW_DIALOG = true;
							preferences.save(Constants.KEY_FLAG_DIALOG, SHOW_DIALOG);
						}else{
							SHOW_DIALOG = false;
							preferences.save(Constants.KEY_FLAG_DIALOG, SHOW_DIALOG);
						}
					}
				});
			}
			
		}else{
			v = convertView;
		}
		
		v.setMinimumHeight(120);
		return v;
	}	
	
	public boolean isServiceRunning() {
	    
		ActivityManager manager = (ActivityManager) contextAct.getSystemService(Context.ACTIVITY_SERVICE);
	    
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if ("fr.univ.context.process.ServiceContext".equals(service.service.getClassName()))
	            return true;
	    }
	    return false;
	}
	
	public void setStateRowsListActivity(int textColor, int alpha, boolean flag){
		
		View v = contextAct.getListView().getChildAt(1);
		
		TextView t1 = (TextView) v.findViewById(R.id.title_set_interval);
		t1.setTextColor(contextAct.getResources().getColor(textColor));
		
		TextView t2 = (TextView) v.findViewById(R.id.subtitle_set_interval);
		
		if ( textColor == R.color.gray)
			t2.setTextColor(contextAct.getResources().getColor(R.color.gray));
		else if (textColor == R.color.white)
			t2.setTextColor(contextAct.getResources().getColor(R.color.blue));		
		
		ImageView im1 = (ImageView) v.findViewById(R.id.im_main_set_interval);
		im1.setAlpha(alpha);
		
		ImageView im2 = (ImageView) v.findViewById(R.id.im_sec_set_interval);
		im2.setAlpha(alpha);
		
		View w = contextAct.getListView().getChildAt(2);
		
		ImageView im3 = (ImageView) w.findViewById(R.id.im_delete_database);
		im3.setAlpha(alpha);
		
		TextView t3 = (TextView) w.findViewById(R.id.title_delete_database);
		t3.setTextColor(contextAct.getResources().getColor(textColor));
		
		View z = contextAct.getListView().getChildAt(3);
		
		TextView t4 = (TextView) z.findViewById(R.id.title_control_dialog);
		t4.setTextColor(contextAct.getResources().getColor(textColor));
		
		TextView t5 = (TextView) z.findViewById(R.id.subtitle_control_dialog);
		
		if ( textColor == R.color.gray)
			t5.setTextColor(contextAct.getResources().getColor(R.color.gray));
		else if (textColor == R.color.white)
			t5.setTextColor(contextAct.getResources().getColor(R.color.blue));
		
		ImageView im4 = (ImageView) z.findViewById(R.id.im_control_dialog);
		im4.setAlpha(alpha);
		
		ToggleButton b = (ToggleButton) z.findViewById(R.id.tb_control_dialog);
		b.setEnabled(flag);
	}
}
